// UniC10_Plugin_SampleDlg.cpp : Implementierungsdatei
//

#include "stdafx.h"
#include "UniC10_Plugin_Sample.h"
#include "UniC10_Plugin_SampleDlg.h"

#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif

#define WM_CREATE_CARD (WM_APP + 77)

/////////////////////////////////////////////////////////////////////////////
// CAboutDlg-Dialogfeld für Anwendungsbefehl "Info"

class CAboutDlg : public CDialog
{
public:
	CAboutDlg();

// Dialogfelddaten
	//{{AFX_DATA(CAboutDlg)
	enum { IDD = IDD_ABOUTBOX };
	//}}AFX_DATA

	// Vom Klassenassistenten generierte Überladungen virtueller Funktionen
	//{{AFX_VIRTUAL(CAboutDlg)
	protected:
	virtual void DoDataExchange(CDataExchange* pDX);    // DDX/DDV-Unterstützung
	//}}AFX_VIRTUAL

// Implementierung
protected:
	//{{AFX_MSG(CAboutDlg)
	//}}AFX_MSG
	DECLARE_MESSAGE_MAP()
};

CAboutDlg::CAboutDlg() : CDialog(CAboutDlg::IDD)
{
	//{{AFX_DATA_INIT(CAboutDlg)
	//}}AFX_DATA_INIT
}

void CAboutDlg::DoDataExchange(CDataExchange* pDX)
{
	CDialog::DoDataExchange(pDX);
	//{{AFX_DATA_MAP(CAboutDlg)
	//}}AFX_DATA_MAP
}

BEGIN_MESSAGE_MAP(CAboutDlg, CDialog)
	//{{AFX_MSG_MAP(CAboutDlg)
		// Keine Nachrichten-Handler
	//}}AFX_MSG_MAP
END_MESSAGE_MAP()

/////////////////////////////////////////////////////////////////////////////
// CUniC10_Plugin_SampleDlg Dialogfeld

CUniC10_Plugin_SampleDlg::CUniC10_Plugin_SampleDlg(CWnd* pParent /*=NULL*/)
	: CDialog(CUniC10_Plugin_SampleDlg::IDD, pParent)
{
	//{{AFX_DATA_INIT(CUniC10_Plugin_SampleDlg)
	m_EDCOMPORT_TEXT = _T("");
	m_lConnectionState = _T("");
	m_lCodingState = _T("");
	m_lDLLVersion = _T("");
	m_edVarValue = _T("");
	m_edCardID = _T("");
	m_lMaxCardID = _T("");
	m_edLanguage = _T("");
	m_lIsPCSC = _T("");
	m_edSearchSleep = _T("");
	m_chbNoGUI = FALSE;
	m_cbTransType = _T("");
	m_edXMLFileName = _T("");
	//}}AFX_DATA_INIT
	// Beachten Sie, dass LoadIcon unter Win32 keinen nachfolgenden DestroyIcon-Aufruf benötigt
	m_hIcon = AfxGetApp()->LoadIcon(IDR_MAINFRAME);
}

void CUniC10_Plugin_SampleDlg::DoDataExchange(CDataExchange* pDX)
{
	CDialog::DoDataExchange(pDX);
	//{{AFX_DATA_MAP(CUniC10_Plugin_SampleDlg)
	DDX_Control(pDX, IDC_LMAXCARDID, m_lMaxCardIDCtrl);
	DDX_Control(pDX, IDC_LCARDID, m_lCardID);
	DDX_Control(pDX, IDC_EDVARVALUE, m_edVarValueCtrl);
	DDX_Control(pDX, IDC_BSETVARVALUE, m_bSetVarValue);
	DDX_Control(pDX, IDC_BCARDID, m_edCardIDCtrl);
	DDX_Control(pDX, IDC_LVVARDATA, m_lvVarData);
	DDX_Control(pDX, IDC_CBREADERNAMES, m_cbReaderNames);
	DDX_Control(pDX, IDC_PBCODING, m_pbCoding);
	DDX_Control(pDX, IDC_LBLOG, m_lbLog);
	DDX_Text(pDX, IDC_EDCOMPORT, m_EDCOMPORT_TEXT);
	DDX_Text(pDX, IDC_LCONNECTIONSTATE, m_lConnectionState);
	DDX_Text(pDX, IDC_LCODINGSTATE, m_lCodingState);
	DDX_Text(pDX, IDC_LDLLVERSION, m_lDLLVersion);
	DDX_Text(pDX, IDC_EDVARVALUE, m_edVarValue);
	DDX_Text(pDX, IDC_BCARDID, m_edCardID);
	DDX_Text(pDX, IDC_LMAXCARDID, m_lMaxCardID);
	DDX_Text(pDX, IDC_EDLANGAUGE, m_edLanguage);
	DDX_Text(pDX, IDC_LISPCSC, m_lIsPCSC);
	DDX_Text(pDX, IDC_EDSEARCHSLEEP, m_edSearchSleep);
	DDX_Check(pDX, IDC_CHBNOGUI, m_chbNoGUI);
	DDX_CBString(pDX, IDC_CBTRANSTYPE, m_cbTransType);
	DDX_Text(pDX, IDC_EDXMLFILENAME, m_edXMLFileName);
	//}}AFX_DATA_MAP
}

BEGIN_MESSAGE_MAP(CUniC10_Plugin_SampleDlg, CDialog)
	//{{AFX_MSG_MAP(CUniC10_Plugin_SampleDlg)
	ON_WM_SYSCOMMAND()
	ON_WM_PAINT()
	ON_WM_QUERYDRAGICON()
	ON_BN_CLICKED(IDC_BCONNECT, OnBconnect)
	ON_BN_CLICKED(IDC_BCHECKCONNECTION, OnBcheckconnection)
	ON_BN_CLICKED(IDC_BDISCONNECT, OnBdisconnect)
	ON_BN_CLICKED(IDC_BPREPARE_CODING, OnBprepareCoding)
	ON_BN_CLICKED(IDC_BCODE, OnBcode)
	ON_BN_CLICKED(IDC_BABORTCODING, OnBabortcoding)
	ON_MESSAGE(WM_CREATE_CARD, OnCreateCard)
	ON_WM_TIMER()
	ON_BN_CLICKED(IDC_BSETVARVALUE, OnBsetvarvalue)
	ON_BN_CLICKED(IDC_BCHECKREGISTRATION, OnBcheckregistration)
	ON_BN_CLICKED(IDC_BCLEARREGISTRATION, OnBclearregistration)
	ON_BN_CLICKED(IDC_BSETLANGUAGE, OnBsetlanguage)
	ON_BN_CLICKED(IDC_BGETCUSTOMERCODE, OnBgetcustomercode)
	ON_CBN_SELCHANGE(IDC_CBREADERNAMES, OnSelchangeCbreadernames)
	ON_BN_CLICKED(IDC_BREADLEGICMASTER, OnBreadlegicmaster)
	ON_BN_CLICKED(IDC_BCHECKLEGICMASTERS, OnBchecklegicmasters)
	ON_BN_CLICKED(IDC_BSEARCHCARDS, OnBsearchcards)
	ON_BN_CLICKED(IDC_BGETLOADEDCOMMISSIONTRANSTYPE, OnBgetloadedcommissiontranstype)
	ON_BN_CLICKED(IDC_BSELECTFILENAME, OnBselectfilename)
	//}}AFX_MSG_MAP
END_MESSAGE_MAP()

/////////////////////////////////////////////////////////////////////////////
// CUniC10_Plugin_SampleDlg Nachrichten-Handler

BOOL CUniC10_Plugin_SampleDlg::OnInitDialog()
{
	CDialog::OnInitDialog();

	// Hinzufügen des Menübefehls "Info..." zum Systemmenü.

	// IDM_ABOUTBOX muss sich im Bereich der Systembefehle befinden.
	ASSERT((IDM_ABOUTBOX & 0xFFF0) == IDM_ABOUTBOX);
	ASSERT(IDM_ABOUTBOX < 0xF000);

	CMenu* pSysMenu = GetSystemMenu(FALSE);
	if (pSysMenu != NULL)
	{
		CString strAboutMenu;
		strAboutMenu.LoadString(IDS_ABOUTBOX);
		if (!strAboutMenu.IsEmpty())
		{	
			pSysMenu->AppendMenu(MF_SEPARATOR);
			pSysMenu->AppendMenu(MF_STRING, IDM_ABOUTBOX, strAboutMenu);
		}
	}

	// Symbol für dieses Dialogfeld festlegen. Wird automatisch erledigt
	//  wenn das Hauptfenster der Anwendung kein Dialogfeld ist
	SetIcon(m_hIcon, TRUE);			// Großes Symbol verwenden
	SetIcon(m_hIcon, FALSE);		// Kleines Symbol verwenden

	// Load UniC10_Plugin DLL
	m_hInst = ::LoadLibrary("UniC10_Plugin.dll");

	if (m_hInst != NULL) {
		// Note: This demo project only implements the UniC10 Plugin API up to version 4.5.
		// For newer functions please check out the demo projects in other languages.
		m_GetDLLVersion = (TGetDLLVersion)GetProcAddress(m_hInst, "GetDLLVersion");
		m_GetRegisteredReaderNames = (TGetRegisteredReaderNames)GetProcAddress(m_hInst, "GetRegisteredReaderNames");
		m_IsPCSCReader = (TIsPCSCReader)GetProcAddress(m_hInst, "IsPCSCReader");
		m_ConnectReader = (TConnectReader)GetProcAddress(m_hInst, "ConnectReader");
		m_CheckReaderConnection = (TCheckReaderConnection)GetProcAddress(m_hInst, "CheckReaderConnection");
		m_DisconnectReader = (TDisconnectReader)GetProcAddress(m_hInst, "DisconnectReader");
		m_SearchCards = (TSearchCards)GetProcAddress(m_hInst, "SearchCards");
		m_PrepareCoding = (TPrepareCoding)GetProcAddress(m_hInst, "PrepareCoding");
		m_GetLoadedCommissionTransType = (TGetLoadedCommissionTransType)GetProcAddress(m_hInst, "GetLoadedCommissionTransType");
		m_ReadLegicMaster = (TReadLegicMaster)GetProcAddress(m_hInst, "ReadLegicMaster");
		m_CheckLegicMasters = (TCheckLegicMasters)GetProcAddress(m_hInst, "CheckLegicMasters");
		m_GetCodingState = (TGetCodingState)GetProcAddress(m_hInst, "GetCodingState");
		m_Code = (TCode)GetProcAddress(m_hInst, "Code");
		m_SleepAndCode = (TSleepAndCode)GetProcAddress(m_hInst, "SleepAndCode");
		m_AbortCoding = (TAbortCoding)GetProcAddress(m_hInst, "AbortCoding");
		m_GetLog = (TGetLog)GetProcAddress(m_hInst, "GetLog");
		m_FreeLog = (TFreeLog)GetProcAddress(m_hInst, "FreeLog");
		m_FreeWideChar = (TFreeWideChar)GetProcAddress(m_hInst, "FreeWideChar");
		m_CheckRegistration = (TCheckRegistration)GetProcAddress(m_hInst, "CheckRegistration");
		m_ClearRegistration = (TClearRegistration)GetProcAddress(m_hInst, "ClearRegistration");
		m_PerformRegistration = (TPerformRegistration)GetProcAddress(m_hInst, "PerformRegistration");
		m_SetLanguage = (TSetLanguage)GetProcAddress(m_hInst, "SetLanguage");
		m_GetCustomerCode = (TGetCustomerCode)GetProcAddress(m_hInst, "GetCustomerCode");

		m_lvVarData.InsertColumn(0, "Area name");
		m_lvVarData.InsertColumn(1, "Format");
		m_lvVarData.InsertColumn(2, "Max");
		m_lvVarData.InsertColumn(3, "Value");
		m_lvVarData.SetColumnWidth(0, LVSCW_AUTOSIZE_USEHEADER);
		m_lvVarData.SetColumnWidth(1, LVSCW_AUTOSIZE_USEHEADER);
		m_lvVarData.SetColumnWidth(2, LVSCW_AUTOSIZE_USEHEADER);
		m_lvVarData.SetColumnWidth(3, LVSCW_AUTOSIZE_USEHEADER);
		m_lvVarData.SetExtendedStyle(m_lvVarData.GetExtendedStyle() | LVS_EX_FULLROWSELECT);

		PWCHAR readerNames;
		m_GetRegisteredReaderNames(readerNames);
		
		CString sNames = CString(readerNames);
		CString sName = "";

		for	(int i = 0; i < sNames.GetLength(); i++) {
			if (sNames.GetAt(i) == 0x02) {
				m_cbReaderNames.AddString(sName);
				sName = "";
			} else {
				sName += sNames.GetAt(i);
			}
		}

		m_FreeWideChar(readerNames);
		
		m_cbReaderNames.SetCurSel(0);
		m_EDCOMPORT_TEXT = "1";

		PWCHAR dllVersion = m_GetDLLVersion();
		m_lDLLVersion = "DLL Version: "+CString(dllVersion);
		m_FreeWideChar(dllVersion);
		
		UpdateData(FALSE);
		UpdateIsPCSCLabel();
		
		SetTimer(1, 100, NULL);
	} else {
		MessageBox("Unable to load UniC10_Plugin.dll. Please copy DLL into the same directory as this application.");
		CDialog::OnOK();
	}

	return TRUE;  // Geben Sie TRUE zurück, außer ein Steuerelement soll den Fokus erhalten
}

void CUniC10_Plugin_SampleDlg::OnSysCommand(UINT nID, LPARAM lParam)
{
	if ((nID & 0xFFF0) == IDM_ABOUTBOX)
	{
		CAboutDlg dlgAbout;
		dlgAbout.DoModal();
	}
	else
	{
		CDialog::OnSysCommand(nID, lParam);
	}
}

// Wollen Sie Ihrem Dialogfeld eine Schaltfläche "Minimieren" hinzufügen, benötigen Sie 
//  den nachstehenden Code, um das Symbol zu zeichnen. Für MFC-Anwendungen, die das 
//  Dokument/Ansicht-Modell verwenden, wird dies automatisch für Sie erledigt.

void CUniC10_Plugin_SampleDlg::OnPaint() 
{
	if (IsIconic())
	{
		CPaintDC dc(this); // Gerätekontext für Zeichnen

		SendMessage(WM_ICONERASEBKGND, (WPARAM) dc.GetSafeHdc(), 0);

		// Symbol in Client-Rechteck zentrieren
		int cxIcon = GetSystemMetrics(SM_CXICON);
		int cyIcon = GetSystemMetrics(SM_CYICON);
		CRect rect;
		GetClientRect(&rect);
		int x = (rect.Width() - cxIcon + 1) / 2;
		int y = (rect.Height() - cyIcon + 1) / 2;

		// Symbol zeichnen
		dc.DrawIcon(x, y, m_hIcon);
	}
	else
	{
		CDialog::OnPaint();
	}
}

// Die Systemaufrufe fragen den Cursorform ab, die angezeigt werden soll, während der Benutzer
//  das zum Symbol verkleinerte Fenster mit der Maus zieht.
HCURSOR CUniC10_Plugin_SampleDlg::OnQueryDragIcon()
{
	return (HCURSOR) m_hIcon;
}

void CUniC10_Plugin_SampleDlg::OnOK() 
{
	CDialog::OnOK();
}

void CUniC10_Plugin_SampleDlg::OnBconnect() 
{
	UpdateData(TRUE);
	BYTE comport = atoi(m_EDCOMPORT_TEXT);

	int cbIndex = m_cbReaderNames.GetCurSel();
	CString strSelected = "";

	if( cbIndex != CB_ERR )
	{
		m_cbReaderNames.GetLBText(cbIndex, strSelected);
		PWCHAR readerName = CStringToPWCHAR(strSelected);
		int err = m_ConnectReader(readerName, comport, 0, 0xFF, 0xFF, 0xFF);
		switch (err) {
		case 0: OnBcheckconnection(); break;
		case 1: MessageBox("Invalid reader name."); break;
		case 2: MessageBox("Unable to connect."); break;
		}
		delete [] readerName; 
	}
}

void CUniC10_Plugin_SampleDlg::OnBcheckconnection() 
{
	if (m_CheckReaderConnection() == 0) {
		m_lConnectionState = "Connected";
	} else {
		m_lConnectionState = "Not connected";
	}
	UpdateData(FALSE);
}

void CUniC10_Plugin_SampleDlg::OnBdisconnect() 
{
	m_DisconnectReader();
}

void CUniC10_Plugin_SampleDlg::OnBprepareCoding() 
{
	UpdateData(TRUE);

	int ecs;
	BYTE hasCardID;
	PWCHAR maxCardID;
	PWCHAR varData;

	PWCHAR fileName = CStringToPWCHAR(m_edXMLFileName);
	HWND hParent;
	if (m_chbNoGUI) {
		hParent = 0;
	} else {
		hParent = GetSafeHwnd();
	}
	int err = m_PrepareCoding(fileName, GetSafeHwnd(), hParent, ecs, hasCardID, maxCardID, varData);
	if (err == 0) {
		m_pbCoding.SetRange(0, ecs);
		m_pbCoding.SetStep(1);
		if (hasCardID) {
			m_edCardIDCtrl.EnableWindow(TRUE);
			m_lCardID.EnableWindow(TRUE);
			m_lMaxCardIDCtrl.EnableWindow(TRUE);
			m_lMaxCardID = "(MAX: " + CString(maxCardID) + ")";
		} else {
			m_edCardIDCtrl.EnableWindow(FALSE);
			m_lCardID.EnableWindow(FALSE);
			m_lMaxCardIDCtrl.EnableWindow(FALSE);
		}

		CString sVarItems = CString(varData);
		CString sVarItem = "";
		CString s = "";
		LVITEM lvi;
		int col;
		int row = 0;

		m_lvVarData.DeleteAllItems();

		if (sVarItems.GetLength() > 0) {
			m_lvVarData.EnableWindow(TRUE);
			m_bSetVarValue.EnableWindow(TRUE);
			m_edVarValueCtrl.EnableWindow(TRUE);
		} else {
			m_lvVarData.EnableWindow(FALSE);
			m_bSetVarValue.EnableWindow(FALSE);
			m_edVarValueCtrl.EnableWindow(FALSE);
		}

		for	(int i = 0; i < sVarItems.GetLength(); i++) {
			if (sVarItems.GetAt(i) == 0x02) {
				col	= 0;
				s = "";
				for	(int j = 0; j < sVarItem.GetLength(); j++) {
					if ((sVarItem.GetAt(j) == 0x03) || (j == sVarItem.GetLength() - 1)) {
						if (j == sVarItem.GetLength() - 1) {
							s += sVarItem.GetAt(j);
						}
						if (col == 0) {
							lvi.mask = LVIF_TEXT;
							lvi.iItem = row;
							lvi.iSubItem = 0;
							lvi.pszText = (LPTSTR)(LPCTSTR)(s);
							m_lvVarData.InsertItem(&lvi);
						} else {
							lvi.iSubItem = col;
							lvi.pszText = (LPTSTR)(LPCTSTR)(s);
							m_lvVarData.SetItem(&lvi);
						}					
						col++;
						s = "";
					} else {
						s += sVarItem.GetAt(j);
					}
				}
				sVarItem = "";
				row++;
			} else {
				sVarItem += sVarItems.GetAt(i);
			}
		}
		m_lvVarData.SetColumnWidth(0, LVSCW_AUTOSIZE_USEHEADER);
		m_lvVarData.SetColumnWidth(1, LVSCW_AUTOSIZE_USEHEADER);
		m_lvVarData.SetColumnWidth(2, LVSCW_AUTOSIZE);
		m_lvVarData.SetColumnWidth(3, LVSCW_AUTOSIZE_USEHEADER);
	} else {
		switch (err) {
		case 1: MessageBox("File not found."); break;
		case 2: MessageBox("No reader connected."); break;
		case 3: MessageBox("Reader cannot code commission."); break;
		case 4: MessageBox("License invalid."); break;
		case 5: MessageBox("CRC validation failed."); break;
		case 6: MessageBox("File deprecated."); break;
		case 7: MessageBox("Transponder type unknown."); break;
		case 8: MessageBox("Commission file invalid."); break;
		case 9: MessageBox("Commission has external data source fields."); break;
		default: MessageBox("Not OK.");
		}
	}
	delete [] fileName;
	m_FreeWideChar(maxCardID);
	m_FreeWideChar(varData);

	UpdateData(FALSE);
}

PWCHAR CUniC10_Plugin_SampleDlg::CStringToPWCHAR(CString str)
{
	int iRes = MultiByteToWideChar(CP_ACP, 0, LPCSTR(str), -1, NULL, 0); 
	wchar_t *szTemp = new wchar_t[iRes]; 

	iRes = MultiByteToWideChar(CP_ACP, 0, LPCSTR(str), -1, szTemp, iRes); 

	return szTemp;
}

void CUniC10_Plugin_SampleDlg::UpdateCodingState() 
{
	UpdateData(TRUE);
	switch (m_GetCodingState()) {
	case 0: m_lCodingState = "Coding State: Offline"; break;
	case 1: m_lCodingState = "Coding State: Online"; break;
	case 2: m_lCodingState = "Coding State: Scan for Card"; break;
	case 3: m_lCodingState = "Coding State: Create Card"; break;
	case 4: m_lCodingState = "Coding State: Wait for remove"; break;
	}
	UpdateData(FALSE);	
}

void CUniC10_Plugin_SampleDlg::UpdateIsPCSCLabel()
{
	UpdateData(TRUE);
	
	int cbIndex = m_cbReaderNames.GetCurSel();
	CString strSelected = "";

	if( cbIndex != CB_ERR )
	{
		m_cbReaderNames.GetLBText(cbIndex, strSelected);
		PWCHAR readerName = CStringToPWCHAR(strSelected);
		int isPCSC = m_IsPCSCReader(readerName);
		delete [] readerName; 
		if (isPCSC == 1) {
			m_lIsPCSC = "(PCSC)";
		} else {
			m_lIsPCSC = "(RS232)";
		}
	}	

	UpdateData(FALSE);
}

void CUniC10_Plugin_SampleDlg::OnBcode() 
{
	int err;

	CString sVarData = "";

	for (int i = 0; i < m_lvVarData.GetItemCount(); i++) {
		sVarData += m_lvVarData.GetItemText(i, 0) + "\003" + m_lvVarData.GetItemText(i, 3) + "\002";
	}

	PWCHAR cardID = CStringToPWCHAR(m_edCardID);
	PWCHAR varData = CStringToPWCHAR(sVarData);

	if (m_edSearchSleep == "") {
		err = m_Code(cardID, varData);
	} else {
		int searchSleep = atoi(m_edSearchSleep);
		err = m_SleepAndCode(cardID, varData, searchSleep);
	}
	switch (err) {
	case 1: MessageBox("Invalid card ID."); break;
	case 2: MessageBox("Invalid var data string."); break;
	case 3: MessageBox("Invalid coding state. Must be 'online'."); break;
	case 4: MessageBox("Invalid license."); break;
	}

	delete [] cardID;
	delete [] varData;
}

void CUniC10_Plugin_SampleDlg::OnBabortcoding() 
{
	if (m_AbortCoding() > 0) {
		MessageBox("Invalid coding state. Must be 'scan for card' or 'wait for remove'.");
	}
}

LRESULT CUniC10_Plugin_SampleDlg::OnCreateCard(WPARAM wParam, LPARAM lParam)
{
	int iMax;
	int iMin;
	m_pbCoding.GetRange(iMin, iMax);
	switch (wParam) {
	case 0: 
		m_lbLog.AddString("Start"); 
		m_pbCoding.SetPos(iMin);
		break;
	case 1: 
		m_lbLog.AddString("Success"); 
		m_pbCoding.SetPos(iMax);
		DisplayLog(lParam);
		m_FreeLog(lParam);
		break;
	case 2: 
		m_lbLog.AddString("Fail"); 
		m_pbCoding.SetPos(iMax);
		DisplayLog(lParam);
		m_FreeLog(lParam);
		break;
	case 3: 
		m_lbLog.AddString("Removed"); 
		m_pbCoding.SetPos(iMax);
		break;
	case 4: 
		m_lbLog.AddString("Error"); 
		m_pbCoding.SetPos(iMax);
		break;
	case 5: 
		m_pbCoding.StepIt(); 
		break;
	}

	return 0;
}

void CUniC10_Plugin_SampleDlg::DisplayLog(LPARAM logHandle)
{
	PWCHAR cardUID;
	int createdDate;
	BYTE codingResult;
	CString sCodingResult;
	PWCHAR shortDesc;
	PWCHAR cardID;
	PWCHAR varData;
	
	if (m_GetLog(logHandle, cardUID, createdDate, codingResult, shortDesc, cardID, varData) == 0) {
		if (codingResult) {
			sCodingResult = "OK";
		} else {
			sCodingResult = "FAIL";
		}
		CTime *tCreatedDate = new CTime(createdDate);
		m_lbLog.AddString(CString(cardUID) + " " + tCreatedDate->Format(_T("%d.%m.%Y %H:%M:%S")) + " " + sCodingResult + " " + CString(shortDesc));
		delete tCreatedDate;
	}
	m_FreeWideChar(cardUID);
	m_FreeWideChar(shortDesc);
	m_FreeWideChar(cardID);
	m_FreeWideChar(varData);
}

void CUniC10_Plugin_SampleDlg::OnTimer(UINT nIDEvent) 
{
	switch (nIDEvent) {
	case 1:
		UpdateCodingState();
		break;
	case 2:
		break;
	}
	CDialog::OnTimer(nIDEvent);
}

void CUniC10_Plugin_SampleDlg::OnBsetvarvalue() 
{
	UpdateData(TRUE);
	POSITION p = m_lvVarData.GetFirstSelectedItemPosition();
	LVITEM lvi;
	if (p != NULL) {
		lvi.mask = LVIF_TEXT;
		lvi.iItem = int(p)-1;
		lvi.iSubItem = 3;
		lvi.pszText = (LPTSTR)(LPCTSTR)(m_edVarValue);
		m_lvVarData.SetItem(&lvi);	
	} else {
		MessageBox("No item selected.");
	}
}

void CUniC10_Plugin_SampleDlg::OnBcheckregistration() 
{
	if (m_CheckRegistration() == 0) {
		MessageBox("OK");
	} else {
		switch (m_PerformRegistration(GetSafeHwnd())) {
		case 0:
			MessageBox("Perform Registration OK");
			break;
		case 1:
			MessageBox("Registration Invalid.");
			break;
		case 2:
			MessageBox("Already registered.");
			break;
		}
	}
}

void CUniC10_Plugin_SampleDlg::OnBclearregistration() 
{
	m_ClearRegistration();
}

void CUniC10_Plugin_SampleDlg::OnBsetlanguage() 
{
	UpdateData(TRUE);

	PWCHAR language = CStringToPWCHAR(m_edLanguage);
	m_SetLanguage(language);
	delete [] language;
}

void CUniC10_Plugin_SampleDlg::OnBgetcustomercode() 
{
	PWCHAR customerCode = m_GetCustomerCode();
	MessageBox(CString(customerCode));
	m_FreeWideChar(customerCode);
}

void CUniC10_Plugin_SampleDlg::OnSelchangeCbreadernames() 
{
	UpdateIsPCSCLabel();
}

void CUniC10_Plugin_SampleDlg::OnBreadlegicmaster() 
{
	switch (m_ReadLegicMaster()) {
	case 0: 
		MessageBox("Master data added successfully.");
		break;
	case 1: 
	    MessageBox("Connected reader does not support Legic media.");
		break;
	case 2: 
		MessageBox("No card in range.");
		break;
	case 3: 
		MessageBox("Invalid coding state.");
		break;
	case 4: 
		MessageBox("Could not add master data.");
		break;
	}
}

void CUniC10_Plugin_SampleDlg::OnBchecklegicmasters() 
{
	PWCHAR missingMasters;
	switch (m_CheckLegicMasters(missingMasters)) {
	case 0:
		MessageBox("Missing masters: "+CString(missingMasters));
		break;	
	case 1: 
	    MessageBox("Connected reader does not support Legic media.");
		break;
	case 2: 
		MessageBox("Loaded commission is no Legic commission.");
		break;
	case 3: 
		MessageBox("Invalid coding state.");
		break;
	case 4: 
		MessageBox("Could not read master data.");
		break;
	}
	m_FreeWideChar(missingMasters);
}

void CUniC10_Plugin_SampleDlg::OnBsearchcards() 
{
	PWCHAR transDesc;
	PWCHAR transType = CStringToPWCHAR(m_cbTransType);
	switch (m_SearchCards(transType, transDesc)) {
	case 0:
		MessageBox("Cards: "+CString(transDesc));
		break;
	case 1:
		MessageBox("No reader connected.");
		break;
	case 2:
		MessageBox("Invalid coding state.");
		break;
	case 3:
		MessageBox("Unknown transponder type.");
		break;
	}	
	m_FreeWideChar(transDesc);
	delete [] transType;
}

void CUniC10_Plugin_SampleDlg::OnBgetloadedcommissiontranstype() 
{
	PWCHAR transType;
	switch (m_GetLoadedCommissionTransType(transType)) {
	case 0:
		MessageBox("Transponder type: "+CString(transType));
		break;
	case 1:
		MessageBox("No commission loaded.");
		break;
	}
	m_FreeWideChar(transType);
}


void CUniC10_Plugin_SampleDlg::OnBselectfilename() 
{
	CFileDialog fOpenDlg(TRUE, "xml", NULL, OFN_HIDEREADONLY|OFN_FILEMUSTEXIST, "UniC10 Plugin Coding Mask (*.xml)|*.xml||", this);
	if (fOpenDlg.DoModal() == IDOK) { 
		m_edXMLFileName = fOpenDlg.GetPathName();
	}
	delete fOpenDlg;
	UpdateData(FALSE);
}
